package com.xuzimian.globaldemo.designpatterns.proxy.dynamic;

import com.xuzimian.globaldemo.designpatterns.proxy.SubjectNoInterfaces;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

import static java.lang.System.out;

public class CglibProxyTest {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        // 设置要代理的目标类
        enhancer.setSuperclass(SubjectNoInterfaces.class);
        // 设置要代理的拦截器
        enhancer.setCallback(new CglibHandler(new SubjectNoInterfaces()));

        // 生成代理类的实例
        SubjectNoInterfaces subject = (SubjectNoInterfaces) enhancer.create();

        subject.processBusiness();
    }

}

class CglibHandler implements MethodInterceptor {
    private Object target;

    public CglibHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args,
                            MethodProxy methodProxy) throws Throwable {
        doBefore();

        Object result = methodProxy.invoke(target, args);

        doAfter();

        return result;
    }

    private void doBefore() {
        out.println("Before ...");
    }

    private void doAfter() {
        out.println("After ...");
    }
}
